$(document).ready(function () {

    $("#uploadImageId").on("click", function () {
        $("#upload-file").click();
    });
    initUploadImg()

});
var blob = null;

/**
 * 上传头像页面初始化方法
 * @returns
 */
function initUploadImg() {
    var options =
        {
            thumbBox: '.thumbBox',
            spinner: '.spinner',
            imgSrc: parent.$("#head-nav-img").attr("src")
        }
    var cropper = $('.imageBox').cropbox(options);
    $('#upload-file').on('change', function () {
        var reader = new FileReader();
        reader.onload = function (e) {
            options.imgSrc = e.target.result;
            cropper = $('.imageBox').cropbox(options);
        }
        reader.readAsDataURL(this.files[0]);
        //this.files = [];
    })
    $('#btnCrop').on('click', function () {
        var img = cropper.getDataURL();
        var data = img.split(',')[1];
        var binary = window.atob(data);

        var array = [];
        for (var i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        blob = new Blob([new Uint8Array(array)], {type: 'image/png'});

        $('.cropped').html('');
        $('.cropped').append('<div style="height:190px;"><img src="' + img + '" align="absmiddle" style="width:180px;margin-top:4px;float:left;"><p>180px*180px</p></div>');
        $('.cropped').append('<div style="height:138px;"><img src="' + img + '" align="absmiddle" style="width:128px;margin-top:4px;float:left;"><p>128px*128px</p></div>');
        $('.cropped').append('<div style="height:74px;"><img src="' + img + '" align="absmiddle" style="width:64px;margin-top:4px;float:left;" ><p>64px*64px</p></div>');
    })
    $('#btnZoomIn').on('click', function () {
        cropper.zoomIn();
    })
    $('#btnZoomOut').on('click', function () {
        cropper.zoomOut();
    })
}

/*
 * 图片上传
 * 注意如果不加processData:false和contentType:false会报错
 */
function uploadImage() {
    var imageForm = new FormData();
    imageForm.append('file', blob);
    //imageForm.append("upfile", $("#chooseImage").get(0).files[0]);
    var url = "/filetransfer/uploadImg";
    $.ajax({
        data: imageForm,
        type: 'POST',
        url: url,
        processData: false,  // 告诉jQuery不要去处理发送的数据
        contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
        success: function (data) {
            var data = JSON.parse(data);
            if (data.success) {
                parent.document.getElementById("userImageId").setAttribute("src", "/" + data.data);
                parent.checkUserLoginInfo();
            } else {
                alert("请先登录");
            }
        },
        error: function () {
            alert("失敗");
        }
    });
}